import React from 'react';
import ReactDOM from 'react-dom';
import { Form, Input, Select, Checkbox, Radio, Row, Col, Icon, Button, DatePicker, InputNumber, Message, Table, Upload, Modal, Popover} from 'antd';
import CostModal from './rentRoomCostModal'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
let uuid = 0;
let nnid = 0;

let SignUpAdd = React.createClass({

  contextTypes: {
    router: React.PropTypes.object
  },

  getInitialState() {
    return {
      loading: false,
      detailList: [],
      furnitList: [], // 家具清单dom
      facilityList: [], // 家具清单数组
      costList: [],  // 费用数据
      costLen: [],
      furnitLen: [],
      meterList: [],
      tempTable: {},
      tempCounts: {},
      ladderList:[],
      costModalVisible: false,
      checkedCost: [],
      checkedCostNew: [], // 有classify
      allCost:[], // 获取的收费项原始数据
      allCostList: {}, // Modal显示所有数据
    }
  },

  componentDidMount() {

    this.fetchFurnit();
   // this.fetchFree();
    this.fetchDetial();
    this.getAllCost();
  },

  // 提交表单
  handleSubmit(e) {
    e.preventDefault();
    let ids = {roomId: this.props.location.state.roomId, rentContractId: this.props.location.state.rentContractId ? this.props.location.state.rentContractId : ''};
    let furnitList = {facilityList: this.setFieldArr(this.state.tempCounts, this.state.furnitLen)};
    let contractFeeItemList = {contractFeeItemList: this.setFieldArr(this.state.tempTable, this.state.costLen)};
    let params = Object.assign({}, ids,  furnitList, contractFeeItemList);
    console.log('params',params);
    this.props.form.validateFields((errors, values) => {
      if (!!errors) {
        console.log('Errors in form!!!');
        return;
      }
      this.setState({
        loading: true,
      });
      Utils.sendAjax({
        url: '/contract/info/add',
        data: JSON.stringify(params),
        method: 'post',
        callback: (result) => {
          if (result.code === '200') {
            Message.success(result.message);
            this.handleBack()
          }else{
            this.setState({
              loading: false,
            });
            Message.error(result.message, 10);
          }
        }
      });
    });
  },

  // 获取家具
  fetchFurnit() {
    let _me = this;
    let params = {roomId: this.props.location.state.roomId};
    Utils.sendAjax({
      url: '/rent/facility/list',
      data: JSON.stringify(params),
      method: 'post',
      callback: (result) => {
        if (result.code === '200') {
          _me.setState({
            furnitList: _me.furnitRender(result.data),
          })
          _me.furnitSetObj(result.data);
          this.fetchMetaRead();

        } else {
          Message.error(result.message, 10)
        }
      }
    });
  },

  // // 获取费用项
  // fetchFree() {
  //   let _me = this;
  //   let params = {roomId: this.props.location.state.roomId};
  //   Utils.sendAjax({
  //     url: '/contract/room/cost/list',
  //     data: JSON.stringify(params),
  //     method: 'post',
  //     callback: (result) => {
  //       if (result.code === '200') {
  //         let newArr = _me.state.costLen;
  //         let newStr = _me.state.tempTable;
  //         result.data.forEach((item) => {
  //           newStr[`costTypeId-${item.id}`] = item.id;
  //           newStr[`costName-${item.id}`] = item.costName;
  //           newStr[`costType-${item.id}`] = '1';
  //           newStr[`depositTotal-${item.id}`] = '0';
  //           newStr[`collectRentsDate-${item.id}`] = null;
  //           newArr.push(item.id);
  //         })
  //         _me.getCheckedCost(result.data);

  //         _me.setState({
  //           costList: result.data,
  //           tempTable: newStr,
          
  //         })
  //       } else {
  //         Message.error(result.message)
  //       }
  //     }
  //   });
  // },

  // 获取费用项的checkedCost数组
  getCheckedCost(data){

    let arry = this.state.checkedCost;
    if (data){
      data.forEach((item) => {
        if(item.id && arry.indexOf(item.id) == '-1'){

          arry.push(`${item.id}`)
        }
        if(item && typeof item != 'object' && arry.indexOf(item) == '-1' ){
          arry.push(`${item}`)
        }
        
      });
    }

    this.setState({
      checkedCost: arry
    });
    // 获取modal展示页checked数据
    this.getCheckedCostNew(arry);
    
  },

  // 获取所有收费项
  getAllCost(){
    Utils.sendAjax({
      url: '/room/cost/list',
      data: JSON.stringify({}),
      method: 'post',
      callback: (result) => {
        if (result.code === '200') {
          let allCostList = this.getAllCostList(result.data);
          this.setState({
            allCost: result.data,
            allCostList: allCostList
          });

        } else {
          Message.error(result.message, 10)
        }
      }
    });
  },

  getAllCostList(data){
    let dataObj = {};
    let classify1 = [];
    let classify2 = {};
    let unit1 = [];
    let unit2 = [];
    let unit3 = [];
    if(data){
      data.forEach((item) => {
        if(item.classify == '1'){ // 固定
          let id = `${item.id}`;
          let obj = {
            'label': item.costName,
            'value': id
          }
          classify1.push(obj);
        }

        if(item.classify == '2'){ // 仪表
          if(item.unit == '1'){// 电费
            
            let id = `${item.id}`;
            let obj = {
              'label': item.costName,
              'value': id
            }
            unit1.push(obj);
          }
          if(item.unit == '2'){// 水费
            
            let id = `${item.id}`;
            let obj = {
              'label': item.costName,
              'value': id
            }
            unit2.push(obj);
          }
          if(item.unit == '3'){// 天然气
            
            let id = `${item.id}`;
            let obj = {
              'label': item.costName,
              'value': id
            }
            unit3.push(obj);
          }
        }
        
      });
    }
    classify2.unit1 = unit1;
    classify2.unit2 = unit2;
    classify2.unit3 = unit3;
    dataObj.classify1 = classify1;
    dataObj.classify2 = classify2;

    return dataObj;
  },

  // 用于modal数据展示
  getCheckedCostNew(data){
    let allCost = this.state.allCost;
    let checkedCostNew = {};
    console.log('data100000000000',data);
    //this.props.getCheckedCost(curChecked);
    let dataObj = {};
    let classify1 = [];
    let classify2 = {};
    let unit1 = [];
    let unit2 = [];
    let unit3 = [];
    if(allCost){
      allCost.forEach((item) => {
        if(data.indexOf(`${item.id}`) != -1){
          
          if(item.classify == '1'){ // 固定
            let id = `${item.id}`;
            
            classify1.push(id);
          }
          if(item.classify == '2'){ // 仪表
            if(item.unit == '1'){// 电费
              
              let id = `${item.id}`;
              
              unit1.push(id);
            }
            if(item.unit == '2'){// 水费
              let id = `${item.id}`;            
              unit2.push(id);
            }
            if(item.unit == '3'){// 天然气
              let id = `${item.id}`;            
              unit3.push(id);
            }
          }

        }
      })
    }
    classify2.unit1 = unit1;
    classify2.unit2 = unit2;
    classify2.unit3 = unit3;
    dataObj.classify1 = classify1;
    dataObj.classify2 = classify2;

    this.setState({
      checkedCostNew: dataObj
    });
  },

  //获取抄表项
  fetchMetaRead() {
    let _me = this;
    let params = {roomId: this.props.location.state.roomId,
      rentContractId: this.props.location.state.rentContractId};
    Utils.sendAjax({
      url: '/room/rent/meter',
      data: JSON.stringify(params),
      method: 'post',
      callback: (result) => {
        if (result.code === '200') {
          _me.setArrFree(result.data);
        } else {
          Message.error(result.message, 10)
        }
      }
    });
  },

  // 获取详情
  fetchDetial() {
    let _me = this;
    let params = {roomId: this.props.location.state.roomId,
      rentContractId: this.props.location.state.rentContractId};
    Utils.sendAjax({
      url: '/contract/cost/list',
      data: JSON.stringify(params),
      method: 'post',
      callback: (result) => {
        if (result.code == '200') {
          let newArr = _me.state.costLen;
          let newStr = _me.state.tempTable;
          if(result.data){
            _me.getCheckedCost(result.data);
            
            result.data.forEach((item) => {
              newStr[`costTypeId-${item.id}`] = item.id;
              newStr[`costTypeName-${item.id}`] = item.costName;
              newStr[`costType-${item.id}`] = '1';
              newStr[`depositTotal-${item.id}`] = '0';
              newStr[`collectRentsDate-${item.id}`] = null;
              newArr.push(item.id);

              item.costTypeName = item.costName;
            })
            
          }
         
          _me.setState({
            costList: result.data,
            tempTable: newStr,
          
          })
        } else {
          Message.error(result.message, 10)
        }
      }
    });
  },

  // 家具数据的转换
  furnitSetObj(data) {
    if (!data[0]) { return }
    let newStr = this.state.tempCounts;
    data.forEach((item, index) => {
      newStr[`facilityNid-${index}`] = item.facilityNid;
      newStr[`facilityName-${index}`] = item.facilityName;
      newStr[`count-${index}`] = item.count;
    })
    this.setState({
      tempCounts: newStr
    })
  },

  // 选择家具
  handleFacility(filed, value) {
    let newStr = this.state.tempCounts;
    newStr[filed] = value;
    this.setState({
      tempCounts: newStr
    })
  },

  rowKey(data) {
    return data.id;
  },

  setFieldArr(obj, len) {
    let newArr = [];
    len.map((k) => {
      let newObj = {};
      for (let o in obj) {
        let arr = o.split('-');
        let key = arr[0];
        if (arr[1] == k && arr[1] !== '') {
          newObj[key] = obj[o];
        }
      }
      if (!newObj) {return}
      newArr.push(newObj);
    })
    return newArr;
  },

  setArrFree(meter) {
    let newArr = [];
    let cost = this.state.costList ? this.state.costList : [];
    if (!meter[0] && !cost[0]) {return }
   

    meter.forEach((item) => {
      let newStr = {};
      cost.forEach((o) => {
        if (item.costTypeId == o.id) {
          newStr[`costTypeName`] = item.costName;
          newStr[`costTypeId`] = item.costTypeId;
          newStr[`scale`] = item.scale?item.scale: '';
          newStr[`collectRentsDate`] = item.scaleTime? item.scaleTime: o.collectRentsDate;
          
        }
      })
      newArr.push(newStr)
    })

    this.setState({
      meterList: newArr
    })
    
  },

  handleTdChange(filed, val) {
    let newStr = this.state.tempTable;
    let key = val.target ? '' : (filed.split('-')[0] !== 'costType' ? filed : ''  );
    let name = filed;
    let value = val.target ? val.target.value : (key ? Utils.formatDate(val) : val) ;

    newStr[name] = value;
    this.setState({
      tempTable:　newStr
    })
  },

  deleteRow(id) {
    let rows = id;
    let data = this.state.costList;
    let checkedCost = this.state.checkedCost;
    let meter = this.state.meterList;
    let tempTable = this.state.tempTable;
    let costLen = this.state.costLen;
    let newData = [];
    let newCheckedCost = [];
    let meterData = [];
    let newCostLen = [];
    let newTempTable = {};
    let newContractFeeItemList = [];
    data.forEach((obj) => {
      if (rows != obj.id) {
        newData.push(obj)
      }
    })

    checkedCost.forEach((obj) => {
      if (rows != obj) {
        newCheckedCost.push(obj)
      }
    });

    meter.forEach((obj) => {
      if (rows != obj.costTypeId) {
        meterData.push(obj)
      }
    })


    costLen.forEach((obj) => {
      if (rows != obj) {
        newCostLen.push(obj);

        for (let o in tempTable) {
          let arr = o.split('-');
          let key = arr[0];
          if (arr[1] == obj && arr[1] !== '') {
            newTempTable[o] = tempTable[o];
          }
        }

      }
    });

    let contractFeeItemList =  this.setFieldArr(this.state.tempTable, this.state.costLen);

    contractFeeItemList.forEach((obj) => {
      if (rows != obj.costTypeId) {
        newContractFeeItemList.push(obj)
      }
    });

    console.log(newCheckedCost);
    this.getCheckedCostNew(newCheckedCost);

    this.setState({
      costList: newData,
      checkedCost: newCheckedCost,
      meterList: meterData,
      costLen: newCostLen,
      tempTable: newTempTable,
      contractFeeItemList: newContractFeeItemList
    })
    
  },

  furnitRender(data) {
    if (!data[0]){ return ;}
    let furnitBox = [];
    let furnitArr = this.state.furnitLen;
    data.forEach((item, index) => {

      let facility = `count-${index}`;
      let furnit = (
        <li className="fl-l furniture-group" key={`list-${index}`}>
          <div className="number-group">
            <Input type="hidden" id="type" name="type" />
            <Input type="hidden" id="facilityNid" name="facilityNid" value={item.facilityNid}/>
            <Input type="hidden" id="facilityName" name="facilityName" value={item.facilityName}/>
            <span className="group-label">{item.facilityName}</span>
            <InputNumber className="group-input" name="count" defaultValue={item.count}
                         onChange={this.handleFacility.bind(this, facility)}
                         min={0} max={100}/>
          </div>
        </li>
      );
      furnitBox.push(furnit);
      furnitArr.push(index);
    })
    this.setState({
      furnitLen: furnitArr
    })
    return furnitBox;
  },

  handleBack() {
    let goPathUrl = '/landlord/rentManage/rentRooms/list';
    let state = this.props.location.state;
    this.context.router.push({pathname: goPathUrl, state: {...state}});
  },

  handleSetFree() {
    this.getCheckedCostNew(this.state.checkedCost);
    this.setState({
      costModalVisible: true
    });
    
  },

  handleHidenModal(){
    this.setState({
      costModalVisible:false
    });
  },

  // 获取阶梯收费详情
  getLadderList(costTypeId){
    Utils.sendAjax({
      url: '/cost/ladder/'+costTypeId,
      callback:(result) => {
        if (result.code === '200') {
          this.setState({
            ladderList: result.data,
          });

        } else {
          notification.error({message: result.message});
        }
      }
    });
  },
  // 获取id、classify关联数组
  get(arry1,arry2){

  },

  // 弹框点击确定后，当前页面收费周期新增行
  addCostList(){
    let tempTable = this.state.tempTable;
    let costLen = this.state.costLen;
    console.log(this.state.checkedCost);
    let checkedCost = this.state.checkedCost;
    let meterList = this.state.meterList;
    let costList = [];
    let newTempTable ={};
    let newMeterList = [];
    let allCost = this.state.allCost;
    let k= costList.length;
    if(checkedCost){
      allCost.forEach((item) => {
        if(checkedCost.indexOf(`${item.id}`) != -1){
            // 构建costList数组
            let obj = {
              'chargeType': item.chargeType,
              'classify': item.classify,
              'costTypeName': item.costName,
              'depositBalance': 0,
              'id': item.id,
              'indexForSort': k++,
              'price': item.price,
              'unit': item.unit,
            }
            costList.push(obj);

            // 构建tempTable对象
            checkedCost.forEach((k) => {
              if(!tempTable){
                for (let o in tempTable) {
                  let arr = o.split('-');
              
                  if (arr[1] == k && arr[1] !== '') { // tempTable中是否存在当前行的值，如果存在，则旧值替换新值
                    newTempTable[o] = tempTable[o];
                  }else{  // tempTable中是否存在当前行的值，如果不存在，则 在newTempTable中追加新值
                    
                    if(k == item.id){

                      // 构建tempTable对象
                      newTempTable[`costTypeId-${k}`] = item.id;
                      newTempTable[`costTypeName-${k}`] = item.costName;
                      newTempTable[`costType-${k}`] = '1';
                      newTempTable[`depositTotal-${k}`] = '0';
                      newTempTable[`collectRentsDate-${k}`] = null;
                    }
                    
                  }
                }  
              }else{
                if(k == item.id){
                  // 构建tempTable对象
                  newTempTable[`costTypeId-${k}`] = item.id;
                  newTempTable[`costTypeName-${k}`] = item.costName;
                  newTempTable[`costType-${k}`] = '1';
                  newTempTable[`depositTotal-${k}`] = '0';
                  newTempTable[`collectRentsDate-${k}`] = null;
                
                }                    
              }                               
            });           
         }

                
      });
    }

    let newArr = [];
    if(costList){
      costList.forEach((item) => {
        if(checkedCost.indexOf(`${item.id}`) != -1){
          let obj = {             
              'classify': item.classify,
              'costTypeName': item.costTypeName,
              'costTypeId': item.id,             
            }
          newArr.push(obj);  
        }
      })
    }

    
    let classify2 = {};
    let classify2Id = [];
    if(newArr){
      newArr.forEach((item) => {
        if(item.classify == '2'){
          classify2[`${item.costTypeId}`] = item.costTypeName;
          classify2Id.push(item.costTypeId);
        }
      });
    }

    if(classify2Id){
      classify2Id.forEach((item) => {
       
            let obj = {}
            obj[`costTypeName`] = classify2[item];
            obj[`costTypeId`] = `${item}`;
            obj[`currScale`] = '';
            obj[`collectRentsDate`] = '';
            newMeterList.push(obj);
        
        });

    }


    this.setState({
      costList: costList,
      costLen: checkedCost,
      tempTable: newTempTable,
      meterList: newMeterList
    });

  },

  render() {
    const { getFieldProps } = this.props.form;
    const _me = this;
    const columns = [
      {
        title: '收费项',
        dataIndex: 'costTypeName'
      },
      {
        title: '计费分类',
        render: (text, record) => {
          return (
            <span>{record.classify == 1 ? '固定' : '仪表'}</span>
          );
        }
      },
      {
        title: '计费方式',
        render: (text, record) => {
          const typeMap = {
            1: '正常收费',
            2: '阶梯收费',
            3: '面积收费'
          }
          return (
            <span>{typeMap[record.chargeType]}</span>
          );
        }
      },
      {
        title: '单价(元)',
        render: (text, record) => {
          let unitMap = {
            '1': '度',
            '2': '吨',
            '3': '立方',
            '4': '平方',
            
          }

          let ladderList = this.state.ladderList;
          let content;
          let ladderBox;
          ladderBox = ladderList.map((item) =>{
            return (
              <Row key={`item-${item.id}`}>
                <Col span={6}>
                  {item.ladderStart}
                </Col>
                <Col span={6}>
                  {item.ladderEnd}
                </Col>
                <Col span={6}>
                  ￥{item.price}
                </Col>
                <Col span={6}>
                  {item.status == 1?'启用':'禁用'}
                </Col>
              </Row>
            );
          });
          content = (
            <div style={{minWidth:300}}>
              <Row>
                <Col span={6}>
                  阶梯开始
                </Col>
                <Col span={6}>
                  阶梯结束
                </Col>
                <Col span={6}>
                  单价
                </Col>
                <Col span={6}>
                  状态
                </Col>
              </Row>
              {ladderBox}
            </div>
          );


          return (
            <span>
           
              {
                record.chargeType != 2 ?
                (
                  record.unit== '5'? 
                  `￥${record.price}`:
                  `￥${record.price}/${unitMap[record.unit]}`
                )
                :
                  (
                    <Popover placement="right" content={content} title="阶梯收费详情" trigger="click">
                      <a onClick={this.getLadderList.bind(this, record.id)}>阶梯收费</a>
                    </Popover>
                  )
              }
            </span>
          )
        }
      },
      // {
      //   title: '收费周期(月/次)',
      //   render: (text, record) => {
      //     let depositTotal = `depositTotal-${record.id}`;
      //     return (
      //       <span>{record.costPeriod ? record.costPeriod : '--'}</span>
      //     )
      //   }
      // },
      {
        title: '押金总额',
        render: (text, record) => {
          let depositTotal = `depositTotal-${record.id}`;
          return (
            <Input id={depositTotal} defaultValue={record.depositBalance ? record.depositBalance.toFixed(2) : '0.00'}
                   onChange={this.handleTdChange.bind(this, depositTotal)} style={{width: 80}} />
          )
        }
      },
      {
        title: '操作',
        render: (text, record) => {
          return (
            <Button className="ant-btn-icon" onClick={this.deleteRow.bind(this, record.id)}  ><Icon type="delete" /></Button>
          )
        }
      }
    ];
    const meterRead = [
      {
        title: '仪表费用项',
        dataIndex: 'costTypeName',
        width: 200
      },
      {
        title: '本次刻度',
        width: 200,
        render: (text, record) => {
          let lastScale = `scale-${record.costTypeId}`;
          return (
            <Input id={lastScale}
                   defaultValue={record.scale}
                   onChange={this.handleTdChange.bind(this, lastScale)} style={{width: 100}} />
          )
        }
      },
      {
        title: '抄表时间',
        width: 200,
        render: (text, record) => {
          let scaleTime = `scaleTime-${record.costTypeId}`;
          return (
            <DatePicker id={scaleTime} defaultValue={record.collectRentsDate}
                        onChange={this.handleTdChange.bind(this, scaleTime)} style={{width: 160}} />
          )
        }
      }
    ];

    let costModalProps = {
      allCostList: this.state.allCostList,
      visible: this.state.costModalVisible,
      checkedCost: this.state.checkedCost,
      checkedCostNew: this.state.checkedCostNew,
      hideModal: this.handleHidenModal,
      getCheckedCost: this.getCheckedCost,
      getCheckedCostNew: this.getCheckedCostNew,
      addCostList: this.addCostList
    }
    console.log('checkedCostNew',this.state.checkedCostNew);
    console.log('checkedCost',this.state.checkedCost);
    return (
      <div >
        <Form inline form={this.props.form}>
          <div className="form-group">
            <h3><span>家具清单</span></h3>
            <Row gutter={24}>
              <Col sm={23} offset={1}>
                <FormItem>
                  <ul>
                    {this.state.furnitList}
                  </ul>
                </FormItem>
              </Col>
            </Row>
          </div>
          <div className="form-group">
            <h3><span>收租设置</span></h3>
            <Row gutter={24}>
              <Col sm={23} offset={1}>
              {
                //<h5 style={{marginBottom: 10}}>收费周期</h5>
              }
                
                <Table rowKey={this.rowKey} columns={columns} dataSource={this.state.costList} pagination={false}/>
                <div style={{marginTop: 20}}>
                  <Button type="primary" onClick={this.handleSetFree} >添加收费项</Button>

                  <CostModal {...costModalProps}
                  />
                </div>
              </Col>
            </Row>
            </div>
            <div className="form-group">
              <h3><span>抄写底表</span></h3>
            <Row gutter={24}>
              <Col sm={23} offset={1}>
                <Table rowKey={(data) => { return data.costTypeId}} columns={meterRead} dataSource={this.state.meterList} pagination={false}/>
              </Col>
            </Row>
          </div>
          <Row gutter={24} style={{margin: 20}}>
            <Col sm={8} offset={3}>
              <FormItem >
                <Button type="primary" loading={this.state.loading} onClick={this.handleSubmit}>保存配置</Button>
                <Button style={{marginLeft: 20}} onClick={this.handleBack}>取消</Button>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <Modal visible={this.state.priviewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" src={this.state.priviewImage} width="500"/>
        </Modal>
      </div>
    );
  }
});

SignUpAdd = Form.create()(SignUpAdd);
export default SignUpAdd;